package com.vedana.bankmobile;

import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

/**
 * Main BankMobile activity.<br/>
 * Tab-based activity with 3 tabs :
 * <ul>
 * <li>Accounts</li>
 * <li>Transfer</li>
 * <li>Portfolio</li>
 * </ul>
 * 
 * @author Didier MOISE
 */
public class BankMobileActivity extends TabActivity {
	private TabHost mTabHost;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bankmobile);

		// Log onto server
		login();

		mTabHost = getTabHost(); // The activity TabHost
		Intent intent; // Reusable Intent for each tab

		// Create tab for accounts
		intent = new Intent().setClass(this, AccountsActivity.class);
		setupTab("Accounts", intent);

		// Create tab for fund transfer
		intent = new Intent().setClass(this, TransferActivity.class);
		setupTab("Transfer", intent);

		// Create tab for portfolio display
		intent = new Intent().setClass(this, PortfolioActivity.class);
		setupTab("Portfolio", intent);

		mTabHost.setCurrentTab(0);
	}

	/**
	 * Log onto BankMobile server
	 */
	private void login() {
		SharedPreferences pref = getSharedPreferences(Constants.PREFS_NAME,MODE_PRIVATE);   
		String username = pref.getString(Constants.PREF_USERNAME, null);
		String password = pref.getString(Constants.PREF_PASSWORD, null);

		if (username == null || password == null) {
			// Display the login activity
			startActivityForResult(new Intent(this, LoginActivity.class), 1);
		}		
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 1 && resultCode != RESULT_CANCELED) {
			getTabHost().setCurrentTab(0);
		} else {
			finish();
		}
	}

	private void setupTab(String tag, Intent intent) {
		View tabview = createTabView(mTabHost.getContext(), tag);
		TabSpec spec = mTabHost.newTabSpec(tag).setIndicator(tabview).setContent(intent);
		mTabHost.addTab(spec);
	}

	private static View createTabView(final Context context, final String text) {
		View view = LayoutInflater.from(context).inflate(R.layout.tabindicator,
				null);
		TextView tv = (TextView) view.findViewById(R.id.tabsText);
		tv.setText(text);
		return view;
	}
}
